import { setToken, getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { login, getInfo, getUserDetailById } from '@/api/user'
// 1.数据
const state = {
  // 1.1 token
  token: getToken(),
  userInfo: {}
}
// 2.同步更新数据
const mutations = {
  // 2.1token
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  // 2.2用户基本信息
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 2.3退出
  userLogout(state) {
    // 将token和用户信息清空
    state.token = ''
    state.userInfo = {}
  }
}
// 3.异步更新
const actions = {
  // 3.1token
  async  userLogin(context, data) {
    // 发送请求
    const res = await login(data)
    context.commit('setToken', res.data)
    Message.success(res.message)
  },
  // 3.2获取用户基本信息
  async getUserInfo(context) {
    const res = await getInfo()
    const res2 = await getUserDetailById(res.data.userId)
    context.commit('setUserInfo', { ...res.data, ...res2.data })
  },
  // 3.3退出
  userLogout(context) {
    context.commit('userLogout')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
